#!/usr/bin/env python3
import os
import json
import re
from pathlib import Path
import subprocess

LOG_DIR = "/home/workspace/gitee/qianrushi/logs"
CONFIG_PATH = '/home/workspace/gitee/qianrushi/orangepi/common/automatic/ecosystem.config.js'
PM2_SCRIPT = '/home/workspace/gitee/qianrushi/orangepi/common/automatic/pm2_script.txt'

# 配置文件模板
CONFIG_TEMPLATE = """module.exports = {{
  apps: {apps_config}
}};"""

def parse_existing_config(config_path: str) -> tuple[list, set]:
    """解析现有配置文件，返回应用列表和已有脚本名称集合"""
    existing_apps = []
    existing_names = set()
    
    if os.path.exists(config_path):
        with open(config_path, "r") as f:
            content = f.read()
            
            # 预处理JS文件为JSON格式
            content = re.sub(
                r"module\.exports\s*=\s*",
                "",
                re.sub(r"//.*?\n", "", content)  # 移除注释
            ).strip(";")
            
            try:
                config = json.loads(content)
                existing_apps = config.get("apps", [])
                existing_names = {app["name"] for app in existing_apps}
            except json.JSONDecodeError:
                print("警告: 无法解析现有配置文件，将重新生成")

    return existing_apps, existing_names

def generate_config():
    # 读取现有配置
    config_path = CONFIG_PATH
    existing_apps, existing_names = parse_existing_config(config_path)
    
    # 读取脚本列表
    with open(PM2_SCRIPT, 'r') as f:
        script_paths = [line.strip() for line in f if line.strip()]
    
    new_apps = []
    for script_path in script_paths:
        if not os.path.exists(script_path):
            print(f"警告: 脚本不存在 {script_path}")
            continue
            
        script_name = Path(script_path).stem
        if script_name in existing_names:
            print(f"跳过已存在配置: {script_name}")
            continue
        
        log_dir = LOG_DIR
        os.makedirs(log_dir, exist_ok=True)  # 自动创建日志目录
        
        new_app = {
            "name": script_name,
            "script": os.path.abspath(script_path),  # 使用绝对路径
            "interpreter": "/usr/bin/python3",
            "interpreter_args": "-u",
            "log_type": "json",
            "autorestart": False,
            "out_file": f"{log_dir}/{script_name}-out.log",
            "error_file": f"{log_dir}/{script_name}-err.log",
            "merge_logs": False,
            "time": True
        }
        new_apps.append(new_app)
    
    # 合并配置
    all_apps = existing_apps + new_apps
    
    # 生成配置文件
    config = CONFIG_TEMPLATE.format(
        apps_config=json.dumps(all_apps, indent=2, ensure_ascii=False)
    )
    
    with open(config_path, 'w') as f:
        f.write(config)
    print(f"配置文件已更新: {config_path} (新增 {len(new_apps)} 个应用)")

    # 执行 PM2 命令 执行玩脚本之后跑此脚本
    run_pm2_commands()

def run_pm2_commands():
    """删除旧实例并启动新配置"""
    try:
        # 删除所有旧的 PM2 实例
        print("已删除所有旧的 PM2 实例")

        # 进入配置文件所在目录（可选，但推荐使用绝对路径）
        config_dir = os.path.dirname(CONFIG_PATH)
        os.chdir(config_dir)

        # 启动新的配置文件
        subprocess.run(["pm2", "start", "ecosystem.config.js"], check=True)
        print("已启动新的 PM2 配置文件")
    except subprocess.CalledProcessError as e:
        print(f"执行 PM2 命令时出错: {e}")

if __name__ == '__main__':
    generate_config()